package com.nan.gbd.library;

import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;

import com.nan.gbd.library.codec.GBMediaNative;
import com.nan.gbd.library.codec.configuration.Configuration;
import com.nan.gbd.library.codec.utils.NetworkUtil;
import com.nan.gbd.library.sip.GBEvent;
import com.nan.gbd.library.sip.RecordBean;
import com.nan.gbd.library.sip.SipUaNative;
import com.nan.gbd.library.utils.Logger;
import com.nan.gbd.library.utils.MainThreadManager;
import com.nan.gbd.library.utils.SpRecordUtils;
import com.nan.gbd.library.utils.usage.Usage;
import com.nan.gbd.library.utils.usage.UsageUtil;

import java.io.File;
import java.util.List;

/**
 * @author NanGBD
 * @date 2019.6.8
 */
public class GB28181ControlManager {


    private Handler mHandlerAsync;
    private static GB28181ControlManager mInstance;
    private Context mContext;

    public static synchronized GB28181ControlManager getInstance() {
        if (mInstance == null) {
            mInstance = new GB28181ControlManager();
        }
        return mInstance;
    }

    public void init() {
        mContext = Configuration.get().getmContext();
        HandlerThread ht = new HandlerThread("asyncThread");
        ht.start();
        //创建handler, 通过绑定一个looper消息管理, 即这个Handler是运行在ht这个线程中(防止阻塞UI线程)
        mHandlerAsync = new Handler(ht.getLooper());
        initSipUa();
        GBMediaNative.getInstance().init();
    }


    /**
     * 初始化国标设备sip
     */
    private long register_start;
    private long register_end;
    private int uid;

    private void initSipUa() {
        mHandlerAsync.post(new Runnable() {
            @Override
            public void run() {
                try {
                    register_start = System.currentTimeMillis();
                    uid = UsageUtil.getUidByPackageName(mContext, mContext.getPackageName());
                    int ret = SipUaNative.init();
                    Logger.e("初始化GB28181 sdk");
                    if (ret != 0) {
                        Logger.e("初始化GB28181 sdk异常");
                        Log.w("gb28181", "初始化GB28181 sdk异常 ret:" + ret);
                        return;
                    }
                    registerToSipServer();
                } catch (Exception e) {
                    e.printStackTrace();
                    Logger.e("初始化GB28181 sdk异常");
                    Log.w("gb28181", "初始化GB28181 sdk异常");

                }
            }
        });
    }

    /**
     * 重新连接服务器
     */
    public void reinit() {
        mHandlerAsync.post(new Runnable() {
            @Override
            public void run() {
                try {
                    int ret = SipUaNative.uninit();
                    Logger.e("配置发生变化----注销 ret:" + ret);
                    mHandlerAsync.removeCallbacksAndMessages(null);
                    initSipUa();
                } catch (Exception e) {
                    e.printStackTrace();
                    Logger.e("初始化GB28181 sdk异常");
                }
            }
        });

    }

    private void registerToSipServer() {
        mHandlerAsync.postDelayed(registerRunnable, 1000);
    }

    private Runnable registerRunnable = new Runnable() {
        @Override
        public void run() {
            if (!NetworkUtil.hasNetwork(mContext)) {
                Logger.e("注册失败,网络不可用");
                registerToSipServer();
                return;
            }
            Logger.e("开始注册GB28181");
            int ret = SipUaNative.register();
            if (ret != 0) {
                Logger.e("注册失败，重新注册");
                registerToSipServer();
                return;
            }
            Logger.e("GB28181注册成功");
            mHandlerAsync.removeCallbacks(registerRunnable);
            JNIBridge.setStatusCallback(statusCallback);
            //开机导入本机录制信息到sdk
            List<RecordBean> recordBeans = SpRecordUtils.getRecordBeanList();
            Logger.e("开机导入本机录制信息到sdk：" + recordBeans.toString());
            if (recordBeans.size() > 0) {
                for (RecordBean recordBean : recordBeans) {
                    if (isFileExists(recordBean)) {
                        SipUaNative.putRecordInfo(recordBean.getStartTime(), recordBean.getEndTime(), recordBean.getAddress(), recordBean.getPath(), recordBean.getPackedFileSize());
                    }
                }
            }


            register_end = System.currentTimeMillis();
            Usage usage = UsageUtil.getApplicationQuerySummary(mContext, register_start, register_end, uid);
            Logger.e("GB28181注册开始时间：" + register_start);
            Logger.e("GB28181注册结束时间：" + register_end);
            Logger.e("当前APP uid：" + uid);
            Logger.e("GB28181注册到服务器流量统计：" + usage.toString());

            MainThreadManager.getMainHandler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    long end = System.currentTimeMillis();
                    long start = end - 60 * 1000;
                    Usage usage = UsageUtil.getApplicationQuerySummary(mContext, start, end, uid);
                    Logger.e("GB28181心跳统计开始时间：" + start);
                    Logger.e("GB28181心跳统计结束时间：" + end);
                    Logger.e("当前APP uid：" + uid);
                    Logger.e("GB28181注册到服务器流量统计：" + usage.toString());
                }
            }, 60 * 1000);

        }
    };

    private boolean isFileExists(RecordBean record) {
        boolean isExists = false;
        if (record == null) return isExists;
        File file = new File(record.getPath());
        if (file.exists()) {
            isExists = true;
        } else {
            Logger.e("清理掉一条无效记录,文件路径:" + record.getPath());
            SpRecordUtils.removeVideoRecordKey(String.valueOf(record.getEndTime()));
            SpRecordUtils.removeKey(String.valueOf(record.getEndTime()));
        }
        return isExists;
    }

    StatusCallback statusCallback = new StatusCallback() {

        @Override
        public boolean onCallback(int code, String name, int key, byte[] param) {

            switch (code) {
                case GBEvent.GB_DEVICE_EVENT_DISCONNECT:
                    Logger.e("连接断开, 可在应用层做自动重新注册");
                    Log.w("gb28181", "连接断开, 可在应用层做自动重新注册");

                    registerToSipServer();
                    break;
                default:
                    break;
            }
            return true;
        }
    };

}
